package com.vitaf.cash.app.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.vitaf.cash.app.R
import com.vitaf.cash.app.common.VitafComAct
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.VitafConfigs
import com.vitaf.cash.app.databinding.VitafActProcessStepsPageBinding
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.ui.fragment.VitafStepContactFmt
import com.vitaf.cash.app.ui.fragment.VitafStepGeneralFmt
import com.vitaf.cash.app.ui.fragment.VitafStepOcrFmt
import com.vitaf.cash.app.ui.fragment.VitafStepSelfieFmt
import com.vitaf.cash.app.ui.fragment.VitafStepWalletFmt
import com.vitaf.cash.app.utils.VitafPickCntUtils
import com.vitaf.cash.app.utils.VitafTitleBarUtil
import com.vitaf.cash.app.utils.helper.VitafProcessHp
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.adapter.VitafStepsApt
import com.vitaf.cash.lib.adapter.VitafOnSingleClickListener
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/18 18:51
 * @Annotation：进件流程
 */
open class VitafProcessStepsAct: VitafComAct(){
    private var _binding: VitafActProcessStepsPageBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit precess steps binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepAdapter: VitafStepsApt? = null

    private var eventStepTitle = ""
    //选择联系人
    var pickContact: VitafPickCntUtils? = null

    companion object {
        private const val INTENT_KEY_AMOUNT = "amount"
        fun start(context: Context, amount: String) {
            val intent = Intent(context, VitafProcessStepsAct::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            context.startActivity(intent)
        }
    }

    override fun createVitafContentView(): View? {
        _binding = VitafActProcessStepsPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeVitafViews() {
        VitafTitleBarUtil.setStatusBarLightMode(this, true)
        getTitleBarManager()
            .setVisibility(View.VISIBLE)
            .setTitle(getString(R.string.gombe_credit_process_step_title))

        getRootViewBinding().rootLayout.getShapeDrawableBuilder()
            .setSolidColor(getColor(R.color.white))
            .intoBackground()

        initGombeCreditStepListView()
        pickContact = VitafPickCntUtils(this)
    }

    override fun setupVitafEventListeners() {
        setRightButtonClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog(eventStepTitle)
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,eventStepTitle)
            }
        })
    }

    override fun loadVitafData() {
        takeGombeCreditProgressSteps()
    }

    /**
     * 初始化步骤列表
     */
    private fun initGombeCreditStepListView() {
        _binding?.let { binding ->
            val layoutManager = LinearLayoutManager(this)
            layoutManager.orientation = RecyclerView.HORIZONTAL
            binding.stepListView.layoutManager = layoutManager
            stepAdapter = VitafStepsApt(binding.stepListView)
            binding.stepListView.adapter = stepAdapter
            binding.stepListView.itemAnimator = DefaultItemAnimator()
            binding.stepListView.isHorizontalScrollBarEnabled = true
        }
    }

    /**
     * 所有步骤已完成 - 进入申贷页
     */
    private fun showGombeCreditProcessStepCompleteViews() {
        VitafApplyAct.start(this)
        finish()
    }

    /**
     * 移除所有步骤
     */
    private fun removeGombeCreditProcessStepAllViews() {
        _binding?.processCurrentLayout?.removeAllViews()
    }

    /**
     * 设置认证步骤进度
     */
    @SuppressLint("SetTextI18n")
    fun showGombeCreditProcessStepProgress(stepTitleList: ArrayList<String>, index: Int) {
        val stepList = arrayListOf<JSONObject>()
        for (i in 0 until stepTitleList.size) {
            val tabObj = JSONObject()
            tabObj.put("stepTitle", stepTitleList[i])
            tabObj.put("selectIndex", index)
            stepList.add(tabObj)
        }
        stepAdapter?.data = stepList

        _binding?.let { binding ->
            val layoutManager = binding.stepListView.layoutManager as LinearLayoutManager
            // 添加布局监听，确保 RecyclerView 已完成布局
            binding.stepListView.post {
                // 计算居中需要的偏移量
                layoutManager.let {
                    val itemWidth = it.getChildAt(0)?.width ?: 0
                    val offset = (binding.stepListView.width - itemWidth) / 2
                    it.scrollToPositionWithOffset(index, offset)
                }
            }
        }
    }

    /**
     * 联系人
     */
    private fun showGombeCreditProcessStepPhoneBookView(data: JSONObject) {
        if (takeGombeCreditLimitAmount().isNotEmpty()){
            //显示额度 = 额度 / 2
            val showAmount = BigDecimal(takeGombeCreditLimitAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
            data.put("creditLimitAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        }
        getFragmentNavigator().replaceFragment(R.id.processCurrentLayout, VitafStepContactFmt(this,data))
    }

    /**
     * 证件照Ocr
     */
    private fun showGombeCreditProcessStepOcrView(data: JSONObject) {
        val showAmount = BigDecimal(takeGombeCreditLimitAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        data.put("creditLimitAmount",BigDecimal(showAmount).multiply(BigDecimal("0.1")).stripTrailingZeros().toPlainString())
        getFragmentNavigator().replaceFragment(R.id.processCurrentLayout, VitafStepOcrFmt(data))
    }

    /**
     * 自拍照
     */
    private fun showGombeCreditProcessStepSelfieView(data: JSONObject){
        getFragmentNavigator().replaceFragment(R.id.processCurrentLayout, VitafStepSelfieFmt(data))
    }

    /**
     * 法语区 绑卡
     */
    private fun showGombeCreditProcessStepBindWalletView(data: JSONObject) {
        getFragmentNavigator().replaceFragment(R.id.processCurrentLayout, VitafStepWalletFmt(data))
    }

    /**
     * 通用样式
     */
    private fun showGombeCreditProcessStepCommonView(data: JSONObject) {
        if (takeGombeCreditLimitAmount().isNotEmpty()){
            //显示额度 = 额度 / 2
            val showAmount = BigDecimal(takeGombeCreditLimitAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
            data.put("creditLimitAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        }
        getFragmentNavigator().replaceFragment(R.id.processCurrentLayout, VitafStepGeneralFmt(data))
    }

    /**
     * 提交
     */
    open fun onGombeCreditProcessStepSubmitAction(params: JSONObject){
        onGombeCreditSubmitProcessStepAction(params)
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    fun showGombeCreditProcessStepSubmitSuccess() {
        //通知刷新总流程
        publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
    }

    override fun onVitafPublishEvent(event: VitafEventData) {
        super.onVitafPublishEvent(event)
        when(event.eventType){
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> {
                takeGombeCreditProgressSteps()
            }
            else -> {

            }
        }
    }

    /**
     * 获取产品额度
     */
    private fun takeGombeCreditLimitAmount(): String{
        return intent.extras?.getString(INTENT_KEY_AMOUNT,"").toString()
    }

    /**
     * 加载流程步骤
     */
    private fun takeGombeCreditProgressSteps(){
        removeGombeCreditProcessStepAllViews()

        val allStepTitles = VitafProcessHp.takeGombeCreditAllStepTitleList()
        //当前进行的步骤
        val curtIndex = VitafProcessHp.takeGombeCreditStepIndex()
        val allSteps = VitafProcessHp.takeGombeCreditAllStepList()
        if (curtIndex == allSteps.size){//所有步骤已完成
            showGombeCreditProcessStepCompleteViews()
            return
        }
        val showTitle = allStepTitles[curtIndex]
        showGombeCreditProcessStepProgress(allStepTitles,curtIndex)

        val processData = VitafProcessHp.takeGombeCreditProcessData()
        eventStepTitle = allSteps[curtIndex]

        //获取对应的key
        val curtKey = allSteps[curtIndex]
        //todo Contact 类型
        if (processData != null && processData.has(curtKey)){
            val stepData = processData.optJSONObject(curtKey)
            stepData?.put("showTitle",showTitle)
            stepData?.put("stepTitle",eventStepTitle)
            if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                showGombeCreditProcessStepPhoneBookView(stepData)
                return
            }
        }

        //todo Ocr证件照样式
        if (curtKey.contains("ocr_info")){
            val stepData = JSONObject()
            stepData.put("showTitle",showTitle)
            stepData.put("stepTitle",eventStepTitle)
            showGombeCreditProcessStepOcrView(stepData)
            return
        }

        //todo Selfie自拍照样式
        if (curtKey.contains("sefie_info")){
            val stepData = JSONObject()
            stepData.put("showTitle",showTitle)
            stepData.put("stepTitle",eventStepTitle)
            showGombeCreditProcessStepSelfieView(stepData)
            return
        }

        //todo Account账户样式（法语地区绑定账号）
        if (curtKey.contains("account_info") && VitafConfigs.isGombeCreditFrench()){
            val stepData = JSONObject()
            stepData.put("showTitle",showTitle)
            stepData.put("stepTitle",eventStepTitle)
            showGombeCreditProcessStepBindWalletView(stepData)
            return
        }
        //常规通用样式
        if (processData != null && processData.has(curtKey)){
            val stepData = processData.optJSONObject(curtKey)
            if (stepData != null) {
                stepData.put("showTitle",showTitle)
                stepData.put("stepTitle",eventStepTitle)
                showGombeCreditProcessStepCommonView(stepData)
            }
        }
    }

    /**
     * 提交数据
     */
    private fun onGombeCreditSubmitProcessStepAction(params: JSONObject){
        showVitafLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                showGombeCreditProcessStepSubmitSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    override fun onStop() {
        super.onStop()
        _binding?.root?.clearFocus()
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}